/* eslint-disable no-param-reassign,array-callback-return */
import { Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import axios from 'axios'
import { getCookie } from './cookie'

const myRequest = axios.create({
  withCredentials: true,
  responseType: 'arraybuffer'
})

myRequest.interceptors.request.use((theRequest) => {
  theRequest.headers.common.Authorization = getCookie('token')
  theRequest.data = theRequest.params
  theRequest.params = { ...theRequest.params, _t: Date.now() }
  return theRequest
})

// 下载请求
export function download(params) {
  const loading = Loading.service({
    lock: true,
    text: '正在下载，请稍后',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return myRequest({
    method: 'post',
    ...params
  })
    .then((res) => {
      const contentDisposition = res.headers['content-disposition']
      const contentType =
        res.headers['content-type'] || 'application/vnd.ms-excel'
      const fileName = contentDisposition
        ? contentDisposition.split('=')[1]
        : 'download.xls'
      // 转为流数据
      const blob = new Blob([res.data], { type: contentType })
      saveAs(blob, decodeURIComponent(fileName))
      Message.success('下载成功')
      return true
    })
    .catch(() => {
      Message.error('下载失败,请重试')
      return false
    })
    .finally(() => {
      loading.close()
    })
}
